<template>
    <div id="agreement">
        <!--搜索框-->
        <div class="interview-header">
            <el-form ref="searchItem" :model="searchItem" :inline="true"  class="demo-form-inline">
                <el-form-item label="订单编号" class="search-item" prop="loanNo">
                    <el-input v-model="searchItem.loanNo" placeholder="订单编号"></el-input>
                </el-form-item>
                <el-form-item label="用户手机号" class="search-item" prop="phone">
                    <el-input v-model="searchItem.phone" placeholder="用户手机号"></el-input>
                </el-form-item>
                <el-form-item label="借款人" class="search-item" prop="realName">
                    <el-input v-model="searchItem.realName" placeholder="借款人"></el-input>
                </el-form-item>
                <el-form-item label="签署状态" prop="protocolStatus">
                    <el-select  v-model.number="searchItem.protocolStatus" placeholder="签署状态">
                        <el-option label="未签署" :value=0></el-option>
                        <el-option label="已签署" :value=1></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="fa-search" @click="loadData()">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button icon="fa-repeat" @click="resetForm()">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!--列表-->
        <div class="table-box">
            <el-table border :data="tableData" tooltip-effect="dark">
                <el-table-column align="center" label="序号" type="index" width="70"></el-table-column>
                <el-table-column align="center" label="状态" prop="protocolStatus"  width="100"></el-table-column>
                <el-table-column align="center" label="申请时间" prop="createTime" width="190"></el-table-column>
                <el-table-column align="center" label="订单编号" width="200">
                    <template scope="scope">
                        <router-link :to="{path: '/apply/borrowerDetails', query: {loanNo: scope.row.loanNo, userNo: scope.row.userNo}}" style="color: #20a0ff">{{scope.row.loanNo}}</router-link>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="借款人" prop="realName" width="110"></el-table-column>
                <el-table-column align="center" label="身份证号码" prop="idcard" width="200"></el-table-column>
                <el-table-column align="center" label="手机号" prop="phone" width="130"></el-table-column>
                <el-table-column align="center" label="车型" prop="carType" width="150"></el-table-column>
                <el-table-column align="center" label="说明" prop="carRemark" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" label="申请额度（元）" prop="loanAmount" width="140"></el-table-column>
                <el-table-column align="center" label="申请期限" prop="loanTime" width="100"></el-table-column>
                <el-table-column align="center" label="业务员" prop="salesman" width="150"></el-table-column>
                <el-table-column align="center" label="面签时间" prop="signTime" width="190"></el-table-column>
                <el-table-column align="center" label="面签人" prop="signUser" width="150"></el-table-column>
                <el-table-column align="center" label="面签额度（元）" prop="signAmount" width="140"></el-table-column>
                <el-table-column align="center" label="借款期限" prop="signLoanTime" width="100"></el-table-column>
                <el-table-column align="center" label="利率（%）" prop="signInterestRate" width="140"></el-table-column>
                <el-table-column align="center" label="综合服务费（元）" prop="signFee" width="160"></el-table-column>
                <el-table-column align="center" label="还款方式" prop="signRepayType" width="100"></el-table-column>
                <el-table-column align="center" label="面签说明" prop="signRemark" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" label="风控初审时间" prop="riskTime" width="170"></el-table-column>
                <el-table-column align="center" label="风控初审人员" prop="riskUser" width="140"></el-table-column>
                <el-table-column align="center" label="风控初审额度（元）" prop="riskAmount" width="180"></el-table-column>
                <el-table-column align="center" label="风控初审借款期限" prop="riskLoanTime" width="160"></el-table-column>
                <el-table-column align="center" label="风控初审利率（%）" prop="riskInterestRate" width="180"></el-table-column>
                <el-table-column align="center" label="风控初审综合服务费（元）" prop="riskFee" width="220"></el-table-column>
                <el-table-column align="center" label="风控初审还款方式" prop="riskRepayType" width="160"></el-table-column>
                <el-table-column align="center" label="风控初审说明" prop="riskRemark" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" label="签署人员" prop="protocolUser" width="150"></el-table-column>
                <el-table-column align="center" label="协议签署" fixed="right" width="200">
                    <template scope="scope">
                        <el-button size="small" @click="returnLoan(scope.row)">退回</el-button>
                        <el-button size="small" type="primary" @click="AgreementSignedOpen(scope.row)" v-if="scope.row.protocolStatus==='未签署'">协议签署</el-button>
                        <el-button  size="small" type="primary" @click="AgreementSignedOpen(scope.row)" v-if="scope.row.protocolStatus==='已签署'">查看协议</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!--分页-->
        <div class="pageNum">
            <el-pagination
                @current-change ="handleCurrentChange"
                @size-change="handleSizeChange"
                :pageNum-sizes="pagesize"
                layout="prev, pager, next, total, sizes"
                :total="total">
            </el-pagination>
        </div>

        <!--协议签署-->
        <el-dialog title="协议签署" :visible.sync="dialogAgreementSigned" class="dialogAgreementSigned">
            <div class="agreementSignedBox">
                <el-button type="primary" @click="sorryDialog = true">在线签署</el-button>
                <el-button @click="openProtocolCheck()">上传协议</el-button>
            </div>
        </el-dialog>

        <!--协议签署暂不支持-->
        <el-dialog title="抱歉" :visible.sync="sorryDialog" class="sorryDialog">
            <p>协议签署暂不支持</p>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="sorryDialog = false">确 定</el-button>
            </div>
        </el-dialog>

        <!--协议上传-->
        <el-dialog title="协议上传" :visible.sync="dialogAgreementUpload" class="dialogAgreementUpload" :before-close="closeprotocolCheck">
            <el-form label-width="80px" :model="protocolCheckInfo" ref="protocolCheck" :rules="ruleProtocolCheck">
                <el-form-item label="上传人员" prop="protocolUser">
                    <el-input :value="protocolUserInfo" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="合同" class="form-item-po" prop="list">
                    <el-upload
                        class="upload-demo"
                        :action="actionUrl"
                        list-type="picture"
                        :on-success="handleSuccess"
                        :on-preview="handlePictureCardPreview"
                        :before-upload="beforeAvatarUpload"
                        :data="DataUploadInfo"
                        :file-list="protocolCheckInfo.list"
                        multiple
                        accept="image/*"
                        :on-remove="handleRemove">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="subProtocolCheck">确 定</el-button>
                    <el-button @click="closeprotocolCheck">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!--图片预览-->
        <el-dialog v-model="dialogVisible" size="tiny">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>

    </div>
</template>

<script>
    import { listLoanProtocol, protocolCheck, keyHex, deleteLoanData, listLoanData, returnLoanCheck } from "@/api/api";
    import CryptoJS from 'crypto-js';
    export default {
        name: "agreement",
        data () {
            return {
                total: 0,
                pagesize: ["10","30","50"],
                // 查询
                searchItem: {
                    loanNo: "",
                    phone: "",
                    realName: "",
                    protocolStatus: "",
                    pageNum: 1,
                    pageSize: 10
                },
                // 列表
                tableData: [],
                // 协议签署；
                dialogAgreementSigned: false,
                // 暂不能协议签署；
                sorryDialog: false,
                // 协议上传
                dialogAgreementUpload: false,
                actionUrl: process.env.API_URL +'/zuul/api-loan/loan/upload/loanData',
                DataUploadInfo: {
                    platformNo: "",
                    loanNo: "",
                    dataType: 2
                },
                protocolUserInfo: "",
                protocolCheckInfo: {
                    loanNo: "",
                    protocolUser: "",
                    list: []
                },
                ruleProtocolCheck: {
                    protocolUser: [
                        { required: true, message: '上传人员不能为空' }
                    ],
                    // 借款合同；
                    list: [
                        { type: 'array', min: 1, required: true, message: '请上传借款合同', trigger: 'change' }
                    ]
                },
                // 图片预览
                dialogImageUrl: '',
                dialogVisible: false
            };
        },
        mounted: function () {
            this.$nextTick(function () {
                if (window.sessionStorage["sysUser"]) {
                    let userInfo = JSON.parse(window.sessionStorage.getItem("sysUser"));
                    this.protocolUserInfo = userInfo.name;
                    this.protocolCheckInfo.protocolUser = userInfo.userNo;
                    this.DataUploadInfo.platformNo = userInfo?userInfo.platformNo:'1';
                } else {
                    this.$router.push({path: '/login'});
                }
                this.loadData();
            });
        },
        watch: {
            $route (to) {
                if(to.name === "agreement"){
                    if (window.sessionStorage["sysUser"]) {
                        let userInfo = JSON.parse(window.sessionStorage.getItem("sysUser"));
                        this.DataUploadInfo.platformNo = userInfo?userInfo.platformNo:'1';
                    }
                    this.loadData();
                }
            }
        },
        methods: {
            // 当前页码
            handleCurrentChange (val) {
                this.searchItem.pageNum = val;
                this.loadData();
            },
            // 每页条数;
            handleSizeChange (val) {
                this.searchItem.pageSize = val;
                this.loadData();
            },
            // 重置
            resetForm () {
                this.$refs.searchItem.resetFields();
            },
            // 协议上传列表、查询
            async loadData () {
                let _this = this;
                await listLoanProtocol(this.searchItem).then(function (res) {
                    let Data = JSON.parse(res.data.ciphertext);
                    if (Data) {
                        _this.tableData = Data.list;
                        _this.total = Data.total;
                        let arr = _this.tableData;
                        for (let i = 0; i < arr.length; i++) {
                            let signStatusArr = ["待面签", "已面签", "面签确认", "面签不通过"];
                            let protocolStatusArr = ["未签署", "已签署"];
                            let DateUnit = ["年", "月", "日"];
                            let signRepayType = ["到期还款", "先息后本", "等额本息", "等额本金"];
                            // 状态
                            arr[i].protocolStatus = protocolStatusArr[arr[i].protocolStatus];
                            // 签署状态
                            arr[i].signStatus = signStatusArr[arr[i].signStatus];

                            // 申请时间
                            if (arr[i].createTime) {
                                arr[i].createTime = _this.formatTime(arr[i].createTime);
                            }

                            // 面签时间
                            if (arr[i].signTime) {
                                arr[i].signTime = _this.formatTime(arr[i].signTime);
                            }

                            // 风控初审时间
                            if (arr[i].riskTime) {
                                arr[i].riskTime = _this.formatTime(arr[i].riskTime);
                            }

                            // 风控初审借款期限
                            if (arr[i].riskLoanTime) {
                                if (arr[i].riskLoanUnit) {
                                    arr[i].riskLoanTime = arr[i].riskLoanTime + DateUnit[arr[i].riskLoanUnit];
                                }
                            }

                            // 风控初审还款方式
                            arr[i].riskRepayType = signRepayType[arr[i].riskRepayType];

                            // 面签期限
                            if (arr[i].signLoanTime) {
                                if (arr[i].loanUnit) {
                                    arr[i].signLoanTime = arr[i].signLoanTime + DateUnit[arr[i].signLoanUnit];
                                }
                            }
                            // 申请期限
                            if (arr[i].loanTime) {
                                if(arr[i].loanUnit === "0" || arr[i].loanUnit === "1" || arr[i].loanUnit === "2"){
                                    arr[i].loanTime = arr[i].loanTime + DateUnit[arr[i].loanUnit];
                                } else {
                                    arr[i].loanTime = arr[i].loanTime + arr[i].loanUnit;
                                }
                            };

                            // 还款方式
                            arr[i].signRepayType = signRepayType[arr[i].signRepayType];
                        }
                    }
                });
            },
            // 打开协议签署
            AgreementSignedOpen (rows) {
                this.protocolCheckInfo.loanNo = rows.loanNo;
                this.DataUploadInfo.loanNo= rows.loanNo;
                this.dialogAgreementSigned = true;
            },
            // 打开协议上传
            openProtocolCheck () {
                this.dialogAgreementUpload = true;
                let _this = this;
                listLoanData({
                    "loanNo": this.protocolCheckInfo.loanNo,
                    "dataType": 2
                }).then((res) => {
                    if (res.data.state.code === "200") {
                        let Data = JSON.parse(res.data.ciphertext);
                        _this.protocolCheckInfo.list = Data;
                        console.log(Data);
                    }
                });
            },
            // 关闭协议上传
            closeprotocolCheck () {
                this.dialogAgreementUpload = false;
                this.dialogAgreementSigned = false;
                this.protocolCheckInfo.protocolUser = "";
                this.fileList = [];
                this.$refs.protocolCheck.resetFields();
            },
            // 上传文件之前
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG && !isPNG) {
                    this.$message.error('只能上传 jpg / png 文件');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return (isJPG || isPNG) && isLt2M;
            },
            // 上传成功
            handleSuccess (response, file, fileList) {
                this.protocolCheckInfo.list = fileList;
                console.log("this.fileList", this.fileList);
                let ciphertext = CryptoJS.TripleDES.decrypt(response.ciphertext, keyHex, {
                    iv: CryptoJS.enc.Utf8.parse(keyHex),
                    mode: CryptoJS.mode.ECB,
                    padding: CryptoJS.pad.Pkcs7
                });
                ciphertext = CryptoJS.enc.Utf8.stringify(ciphertext);
                response.ciphertext = JSON.parse(ciphertext);
                file.dataNo = response.ciphertext.dataNo;
                // console.log("response", response);
                console.log("fileList", file.response.ciphertext.dataNo);
            },
            // 删除图片
            handleRemove (file) {
                console.log(file);
                deleteLoanData({
                    "platformNo": this.DataUploadInfo.platformNo,
                    "loanNo": this.DataUploadInfo.loanNo,
                    "dataNo": file.dataNo
                }).then((res) => {
                    console.log(res);
                });
            },
            // 协议上传；
            subProtocolCheck () {
                let _this = this;
                this.$refs.protocolCheck.validate((valid) => {
                    if (valid) {
                        this.postProtocolCheck();
                    } else {
                        return false;
                    }
                });
            },
            async postProtocolCheck () {
                let _this = this;
                await protocolCheck({
                    loanNo: this.protocolCheckInfo.loanNo,
                    protocolUser: this.protocolCheckInfo.protocolUser
                }).then((res) => {
                    if (res.data.state.code === "200") {
                        _this.$message({
                            message: "成功",
                            type: 'success'
                        });
                        _this.loadData();
                        _this.closeprotocolCheck();
                    } else {
                        _this.$message({
                            message: res.data.state.message,
                            type: 'error'
                        });
                    }
                });
            },
            // 图片预览
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            // 退回
            returnLoan (row) {
                let _this = this;
                this.$confirm('是否退回?', '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                }).then(() => {
                    returnLoanCheck({
                        "loanNo": row.loanNo
                    }).then((res) => {
                        if (res.data.state.code === "200") {
                            _this.$message({
                                message: "成功",
                                type: 'success'
                            });
                            _this.loadData();
                        } else {
                            _this.$message(res.data.state.message);
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            }
        }
    };
</script>

<style lang="scss">
    #agreement{
        .interview-header{
            border: 1px solid #eee;
            margin:20px;
            padding:22px 0 0 20px;
            min-width: 1200px;
            box-sizing: border-box;
            .search-in{
                .search-item{
                    margin-right: 30px;
                }
            }
        }
        .table-box{
            margin:20px;
            min-width: 1200px;
            .add-btn{
                margin: 20px;
                .el-icon-plus{
                    font-size:12px;
                }
            }
            .export-btn{
                padding: 15px;
            }
        }
        .pageNum{
            text-align: right;
            padding:0 10px;
            .el-pagination{
                padding: 0;
            }
        }
        .costAccountingDialog{
            .costAccountingTable{
                width: 800px;
                position: fixed;
                top: 20%;
                left: 50%;
                margin-left: -400px;
                background: #fff;
            }
            .costAccountingBox{
                margin: 0 auto;
                border-top: 1px solid #eee;
                h3{
                    padding: 10px 0;
                    text-align: center;
                    border-bottom: 1px solid #eee;
                }
                .costTableInpu{
                    text-align: center;
                    padding: 20px 0;
                }
                .costTableItme{
                    padding: 0 30px;
                    margin-top:20px;
                    table{
                        border-spacing:0;
                        width: 100%;
                        text-align: center;
                        th{
                            padding: 10px 0;
                            background: #f2f2f2;
                        }
                        th,td{
                            border: 1px solid #eee;
                        }
                        td{
                            padding:10px 0;
                        }
                    }
                }
                .costAccountingBotton{
                    margin: 20px 0;
                    text-align: center;
                    button{
                        width: 180px;
                        margin: 0 30px;
                    }
                }
            }

        }
        .dialogAgreementSigned{
            .agreementSignedBox{
                width: 190px;
                margin:20px auto;
            }
        }
        .dialogAgreementUpload{
            .el-form{
                width: 420px;
                margin: 0 auto;
                .el-form-item{
                    .el-input{
                        width: 200px;
                    }
                    .file_btn{
                        width:200px;
                        text-align: center;
                        position: relative;
                        border: 1px solid #bfcbd9;
                        border-radius: 4px;
                        .file-input{
                            opacity: 0;
                            width: 100%;
                            height: 100%;
                            position: absolute;
                            left:0;
                            top:0;
                        }
                    }
                    .file_btn:hover{
                        border: 1px solid #20a0ff;
                    }
                    .upload_warp_img{
                        margin-top:22px;
                        .upload_warp_img_div{
                            width: 146px;
                            height: 146px;
                            border: 1px dashed #d9d9d9;
                            border-radius: 6px;
                            display: inline-block;
                            margin-right:15px;
                            margin-bottom: 15px;
                            position: relative;
                            img{
                                width: 146px;
                                height: 146px;
                                position: absolute;
                                left: 0;
                                top:0;
                            }
                            .close{
                                width: 5px;
                                height: 5px;
                                position: absolute;
                                right: 4px;
                                top: -10px;
                                font-size: 18px;
                                color: #ccc;
                                cursor: pointer;
                            }
                            .close:hover{
                                color: #20a0ff;
                            }
                        }
                    }
                }
            }
        }
        .dialogAssetsConfirmed{
            .el-form{
                width: 420px;
                margin: 0 auto;
                .el-form-item{
                    .el-input{
                        width: 200px;
                    }
                    .tips{
                        color: #999999;
                    }
                }
            }
        }
    }
</style>
